package cn.lpq.magnetsearch.impl;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.hutool.core.net.URLEncoder;
import cn.hutool.json.JSONUtil;
import cn.lpq.magnetsearch.AbstractMagentSearch;
import cn.lpq.magnetsearch.MagentInfo;

public class AnidexMagentSearch extends AbstractMagentSearch {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private String queryUrl = "https://anidex.info/?q=";

	private List<MagentInfo> magentInfolist = new ArrayList<MagentInfo>();

	@Override
	public List<MagentInfo> magentSearch(String keyword) {
		magentInfolist.clear();
		try {
			// keyword = URLEncoder.createDefault().encode(keyword,
			// Charset.defaultCharset());
			Connection.Response execute = Jsoup.connect(queryUrl + keyword).ignoreContentType(true).execute();
			// 获取返回数据
			String body = execute.body();
			Document doc = Jsoup.parse(body);
			Elements links = doc.select("table.table tr");
			for (Element link : links) {
				String fileName = link.select("span.span-1440").text();
				String magent = link.select("a[href^=magnet]").attr("href");
				String fileSize = link.select("td.td-992:eq(1)").text();
				MagentInfo magentInfo = new MagentInfo(fileName, fileSize, magent);
				magentInfolist.add(magentInfo);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("解析发生错误！！！");
		} finally {

		}
		return magentInfolist;
	}

	public static void main(String[] args) throws IOException {
		AbstractMagentSearch s = new AnidexMagentSearch();
		System.out.println(JSONUtil.toJsonStr(s.magentSearch("阿丽塔")));
	}

}
